
function readl(hdl)
	local S="" local s local r
	while 1 do
		if hdl then
			s,r=read(hdl,1)
		else
			s,r=read(1)
		end
		if not s then
			if S=="" then
				return s,r
			else
				return S
			end
		else
			S=S..s
			if s=="\n" then
				return S
			end
		end
	end
end

function bkm(s)
	last = strsub( s, -1)
	if last=="b" then
		return strsub(s,1,-2) * 512
	end
	if last=="k" then
		return strsub(s,1,-2) * 1024
	end
	if last=="m" then
		return strsub(s,1,-2) * 1048576
	end
	return tonumber(s)
end

function fail(s,m)
	_ALERT("\nERROR\n")
	if s then
	_ALERT(s.."\n")
	end
	if m then
	_ALERT(m.."\n")
	end
	_ALERT("\n")
	exit(-1)
end

function check(t,c,s) -- use var args
-- n is nil bad
-- v is nil good
-- z is 0 good
-- m is the message
	if (t.n and (not c))
	or (t.v and c)
	or (t.z and (c~=0))
	then
		fail(s,m)
	end
	return c,s
end
function checknil(c)
	if c then
		fail(c)
	end
end

function tohex(s)
	local r = ""
	for i=1, strlen(s)
	do
		r=r..format("%02x",strbyte(strsub(s,i,i)))
	end
	return r
end

function strfindlast(s,c)
	-- for i=-1, -strlen(s), -1
	for i=strlen(s), 1, -1
	do
		if strsub(s,i,i)==c then
			return i
		end
	end
	return nil
end

function dirname(s)
a=strsub(arg[1],1,strfindlast(s,"/")-1)
if a=="" then a="/" end
if a==nil then a="." end
return a
end

function basename(s)
a=strsub(arg[1],strfindlast(s,"/")+1)
if a=="" or a==nil then a=arg[1] end
return a
end

-- takes a table with (optchar, numarg)
-- returns a table with (optchar, value ("" if none))
--  , index of first non-option argument 
--
-- initially only supports "cut -f 1" or "cut -c 1-7" type arg
--
function getopts (optdef)
for a,b in optdef
do
end
	idx=1
	local opts={}
	lim=getn(arg)
	while (arg[idx])
	do
		if arg[idx] == "--" then
			break
		end
		if strsub(arg[idx],1,1) == "-" and strsub(arg[idx],2,2)
		then
			curopt = strsub(arg[idx],2,2)
			if optdef[curopt]
			then
				if optdef[curopt] > 0
				then
					-- support for 'cut -f1' here 
					if optdef.filesonly then
						arg[idx] = nil
					end
					idx = idx + 1
					-- support for 'prog -x asdf qwer' here
					opts[curopt] = arg[idx]
				else
					opts[curopt] = ""
					-- support for 'rm -rf' type arg here
				end
			else
				mysteryopt = strsub(arg[idx],2)
			end
			if optdef.filesonly then
				arg[idx] = nil
			end
		else
			break
		end
	idx = idx + 1	
	end
	if optdef.filesonly then
		arg.n=nil
		arg[0]=nil
	end
	return opts, idx, mysteryopt
end
